import md5 from 'js-md5'
import store from '../store'

const SANSHAN_APPID = 'youzhiyuan'
const SANSHAN_APPKEY = 'f32fb717-a2c2-475e-91df-19a66bc4968d'

export function getSignedParams (params) {
  var paramMap = {}
  paramMap['nonceStr'] = createNonceStr()
  paramMap['appId'] = SANSHAN_APPID
  paramMap['timeStamp'] = getTimeStamp()
  paramMap['reqData'] = JSON.stringify(params)
  paramMap['operator'] = store.getters.operator || '[]'
  var signstr = obj2str(paramMap)
  signstr = signstr + '&appKey=' + SANSHAN_APPKEY
  var sign = md5(signstr).toLowerCase()
  paramMap['sign'] = sign
  return paramMap
}

// 产生随机字符串
function createNonceStr () {
  return Math.random().toString(36).substr(2, 15)
}

// 创建时间戳
function getTimeStamp () {
  return parseInt(new Date().getTime() / 1000) + ''
}

// 对象转字符串，用于签名
function obj2str (args) {
  var keys = Object.keys(args)
  keys = keys.sort() // 参数名ASCII码从小到大排序（字典序）
  var newArgs = {}
  keys.forEach(function (key) {
    if (args[key] !== '' && args[key] !== 'undefined') { // 如果参数的值为空不参与签名
      newArgs[key] = args[key] // 参数名区分大小写
    }
  })
  var string = ''
  for (var k in newArgs) {
    string += '&' + k + '=' + newArgs[k]
  }
  string = string.substr(1)
  return string
}
